package com.zhoug.demo.sendpush;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.google.gson.reflect.TypeToken;
import com.zhoug.common.content.Optional;
import com.zhoug.common.framework.rxjava2.SchedulerUtils;
import com.zhoug.common.utils.JsonUtils;
import com.zhoug.common.utils.MD5Utils;
import com.zhoug.common.utils.StringUtils;
import com.zhoug.common.utils.TimeUtils;
import com.zhoug.common.utils.ToastUtils;
import com.zhoug.demo.sendpush.huawei.AndroidConfig;
import com.zhoug.demo.sendpush.huawei.AndroidNotification;
import com.zhoug.demo.sendpush.huawei.ClickAction;
import com.zhoug.demo.sendpush.huawei.HuaweiMessage;
import com.zhoug.demo.sendpush.huawei.HuaweiMessageBody;
import com.zhoug.demo.sendpush.huawei.HuaweiPushServer;
import com.zhoug.demo.sendpush.huawei.HuaweiPushToken;
import com.zhoug.demo.sendpush.huawei.Notification;
import com.zhoug.demo.sendpush.huawei.SendResponseBody;
import com.zhoug.logging.Logger;
import com.zhoug.zmui.ZMUIAnimations;
import com.zhoug.zmui.dialog.list.ZMUIListDialog;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.disposables.Disposable;

/**
 * @description: 类的简要描述
 * @author: 35574
 * @date: 2025/11/4 17:33
 */
public class MainActivity extends MyBaseActivity {
    private static final String TAG = ">>>MainActivity";
    private static final String DEFAULT_APP_TOKEN = "IQAAAACy0-jGAADNDmbdJUF-gyMQw_M4VHCXasawaDTracUSZehwx50BqnIHC8OosKr5FckiPzEmIlnSPRVQM2RFayREx_l2a0JQcuptDM6N6XhtyQ";
    private static final String DEFAULT_PROJECTID = "461323198428929507";
    private static final String DEFAULT_CLIENTID = "112331803";
    private static final String DEFAULT_CLIENTSECRET = "073f1dd261992e05c03abfaa30a3989b80cba69a470678dc25743a65f4eb4257";
    private final List<PushConfig> mPushConfigs = new ArrayList<>();
    private PushConfig mPushConfig;

    private final List<String> mAppTokens = new ArrayList<>();
    private Button mBtnSend;
    private Button mBtnAuthentication;
    private EditText mEtToken;
    private Button mBtnSaveAppToken;
    private Switch mSwitchMessageType;
    private EditText mEtProjectId;
    private EditText mEtClientId;
    private EditText mEtClientSecret;
    private TextView mBtnSelectPushConfig;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void findViews() {

        mBtnSend = findViewById(R.id.btn_send);
        mBtnAuthentication = findViewById(R.id.btn_authentication);
        mEtToken = findViewById(R.id.et_token);
        mBtnSaveAppToken = findViewById(R.id.btn_saveAppToken);
        mSwitchMessageType = findViewById(R.id.switch_messageType);
        mEtProjectId = findViewById(R.id.et_ProjectId);
        mEtClientId = findViewById(R.id.et_ClientId);
        mEtClientSecret = findViewById(R.id.et_ClientSecret);
        mBtnSelectPushConfig = findViewById(R.id.btn_selectPushConfig);
    }


    @Override
    protected void onCreate1(Bundle savedInstanceState) {
        PushConfig pushConfig = SharedPre.getHuaweiPushConfig();
        if (pushConfig != null) {
            initConfig(pushConfig);
        }
        //选择配置文件
        mBtnSelectPushConfig.setOnClickListener(v -> {
            ZMUIListDialog<PushConfig> listDialog = new ZMUIListDialog<PushConfig>(this) {

                @Override
                public String getText(PushConfig pushConfig) {
                    return pushConfig.getName();
                }
            };
            listDialog.setData(mPushConfigs);
            listDialog.setWindowAnimations(ZMUIAnimations.ANIM_DOWN);
            listDialog.setFullWidth(true);
            listDialog.setAttributes(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
            listDialog.setOnItemClickListener(i -> {
                listDialog.dismiss();
                PushConfig pushConfig1 = listDialog.getItemData(i);
                initConfig(pushConfig1);
            });
            listDialog.show();
        });
        mBtnSaveAppToken.setOnClickListener(v -> {
            String tokens = null;
            String projectId = null;
            String clientId = null;
            String clientSecret = null;
            //配置token
            Editable text = mEtToken.getText();
            if (text != null) {
                tokens = text.toString();
            }
            if (StringUtils.isNullOrEmpty(tokens)) {
                ToastUtils.toastLong("token不能为空");
                return;
            }

            //配置ProjectId
            text = mEtProjectId.getText();
            if (text != null) {
                projectId = text.toString();
            }
            //配置clientId
            text = mEtClientId.getText();
            if (text != null) {
                clientId = text.toString();
            }
            //配置clientSecret
            text = mEtClientSecret.getText();
            if (text != null) {
                clientSecret = text.toString();
            }
            if (StringUtils.isNullOrEmpty(projectId)) {
                ToastUtils.toastLong("projectId不能为空");
                return;
            }
            if (StringUtils.isNullOrEmpty(clientId)) {
                ToastUtils.toastLong("clientId不能为空");
                return;
            }
            if (StringUtils.isNullOrEmpty(clientSecret)) {
                ToastUtils.toastLong("clientSecret不能为空");
                return;
            }
            PushConfig pushConfig1 = new PushConfig();
            pushConfig1.setProjectId(projectId);
            pushConfig1.setClientId(clientId);
            pushConfig1.setClientSecret(clientSecret);
            pushConfig1.setAppTokens(tokens);
            initConfig(pushConfig1);
        });
        mBtnAuthentication.setOnClickListener(v -> {
            HuaweiPushToken huaweiToken = getHuaweiPushServerToken();
            if (huaweiToken != null && !huaweiToken.isExpired()) {
                new AlertDialog.Builder(this)
                        .setMessage("token未过期,是否重新鉴权")
                        .setTitle("警告")
                        .setPositiveButton("重新鉴权", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                authentication();
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();

            } else {
                authentication();
            }


        });
        mBtnSend.setOnClickListener(v -> sendMessage());
        initPushConfigFromFile();
    }

    private void initPushConfigFromFile() {
        Disposable disposable = Observable.create(new ObservableOnSubscribe<Optional<List<PushConfig>>>() {
                    @Override
                    public void subscribe(ObservableEmitter<Optional<List<PushConfig>>> emitter) throws Exception {
                        InputStream inputStream = null;
                        try {
                            inputStream = getResources().openRawResource(R.raw.pushconfigs);

                            byte[] bytes = Utils.readAllBytes(inputStream);
                            String config = new String(bytes, 0, bytes.length, StandardCharsets.UTF_8);
                            Logger.d(TAG, "initPushConfig: config:" + config);
                            List<PushConfig> pushConfigs = JsonUtils.fromJsonList(config, new TypeToken<List<PushConfig>>() {
                            }.getType());
                            emitter.onNext(Optional.create(pushConfigs));
                        } catch (Resources.NotFoundException e) {
                            emitter.onError(new Throwable("找不到配置文件:pushconfigs.json"));
                        } catch (IOException e) {
                            emitter.onError(new Throwable("初始化配置出错:" + e.getMessage()));
                        } finally {
                            if (inputStream != null) {
                                inputStream.close();
                            }
                            emitter.onComplete();
                        }
                    }
                }).subscribeOn(SchedulerUtils.io())
                .observeOn(SchedulerUtils.ui())
                .subscribe(opt -> {
                    List<PushConfig> pushConfigs = opt.get();
                    if (pushConfigs == null || pushConfigs.isEmpty()) {
                        ToastUtils.toastLong("配置文件错误");
                    } else {
                        mPushConfigs.clear();
                        mPushConfigs.addAll(pushConfigs);
                        if (mPushConfig == null) {
                            initConfig(pushConfigs.get(0));
                        }
                    }
                }, ToastUtils::toastLong);
    }


    private void initConfig(@NonNull PushConfig config) {
        HuaweiPushServer.setProjectId(config.getProjectId());
        HuaweiPushServer.setClientId(config.getClientId());
        HuaweiPushServer.setClientSecret(config.getClientSecret());
        mAppTokens.clear();
        String appTokens = config.getAppTokens();
        if (!StringUtils.isNullOrEmpty(appTokens)) {
            String[] split = appTokens.split(",");
            for (String token : split) {
                token = token.trim();
                if (!TextUtils.isEmpty(token)) {
                    mAppTokens.add(token);
                }
            }
        }
        SharedPre.keepHuaweiPushConfig(config);
        mEtProjectId.setText(config.getProjectId());
        mEtClientId.setText(config.getClientId());
        mEtClientSecret.setText(config.getClientSecret());
        mEtToken.setText(config.getAppTokens());

        mPushConfig = config;
        HuaweiPushToken huaweiToken = getHuaweiPushServerToken();
        if (huaweiToken == null || huaweiToken.isExpired()) {
            authentication();
        }
    }


    private HuaweiPushToken getHuaweiPushServerToken() {
        if (mPushConfig == null) return null;
        return SharedPre.getHuaweiServerToken(MD5Utils.getMD5(mPushConfig.getClientId() + "_" + mPushConfig.getClientSecret()));
    }


    /**
     * 鉴权
     */
    private void authentication() {
        ToastUtils.toastLong("开始鉴权");
        HuaweiPushServer.authentication(new DataCallback<HuaweiPushToken>() {
            @Override
            public void onSuccess(HuaweiPushToken token) {
                ToastUtils.toastShort("鉴权成功");
                SharedPre.keepHuaweiServerToken(MD5Utils.getMD5(token.getClientId() + "_" + token.getClientSecret()), token);
            }

            @Override
            public void onFailure(String error) {
                ToastUtils.toastShort(error);
            }
        });
    }

    /**
     * 向指定应用发送显式广播
     * @param targetPackageName 目标应用的包名
     * @param targetReceiverClass 目标广播接收器的全类名
     */
    private void sendExplicitBroadcastToApp(String targetPackageName, String targetReceiverClass) {
        Logger.d(TAG, "sendExplicitBroadcastToApp: 向 " + targetPackageName + " 发送显式广播");
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("com.zhoug.push.MESSAGING_EVENT"); // Action仍然可以设置，但非必须
        broadcastIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        broadcastIntent.putExtra("sendPackageName", getPackageName());
        // 关键：设置组件名，将隐式广播变为显式广播
        ComponentName component = new ComponentName(targetPackageName, targetReceiverClass);
        broadcastIntent.setComponent(component);

        sendBroadcast(broadcastIntent);
    }

    /**
     * 发送消息
     */
    private void sendMessage() {
//        if (true) {
//            //发送广播
//            Logger.d(TAG, "sendMessage: 发送广播");
//            // 发送给 clientApp2
//            sendExplicitBroadcastToApp("com.zhoug.demo.pusha",
//                    "com.zhoug.demo.pusha.PushMessageReceiver");
//
//            // 发送给 clientApp1
//            sendExplicitBroadcastToApp("com.zhoug.demo.push",
//                    "com.zhoug.demo.push.PushMessageReceiver");
//
//            // 发送给 clientApp1
//            sendExplicitBroadcastToApp("com.zhoug.demo.sendpush",
//                    "com.zhoug.demo.sendpush.PushMessageReceiver");


//            String packageName = getPackageName();
//            Intent broadcastIntent = new Intent("com.zhoug.push.MESSAGING_EVENT");
//            broadcastIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
//            broadcastIntent.putExtra("sendPackageName", packageName);
//            broadcastIntent.setPackage(packageName);
////            broadcastIntent.setComponent(new ComponentName("com.zhoug.demo.pusha", "com.zhoug.demo.pusha.PushMessageReceiver"));
//            sendBroadcast(broadcastIntent);

//            return;
//        }

        if (mAppTokens.isEmpty()) {
            ToastUtils.toastLong("请设置appToken");
            return;
        }
        String currentTime = TimeUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
        HuaweiPushToken huaweiToken = getHuaweiPushServerToken();
        if (huaweiToken == null || huaweiToken.isExpired()) {
            ToastUtils.toastLong("token已过期,请重新鉴权");
            return;
        }
        boolean touchuanMessage = mSwitchMessageType.isChecked();

        HuaweiMessageBody messageBody = new HuaweiMessageBody();
        messageBody.setValidate_only(false);
        HuaweiMessage huaweiMessage = new HuaweiMessage();
        messageBody.setMessage(huaweiMessage);
        huaweiMessage.setToken(mAppTokens);
        //穿透消息
        if (touchuanMessage) {
            huaweiMessage.setData("待办任务,请尽快处理:" + currentTime);
        } else {
            //通知消息
            Notification notification = new Notification();
            notification.setTitle("待办任务");
            notification.setImage("https://img0.baidu.com/it/u=3503816777,292249526&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400");
            notification.setBody("你有新的待办任务请及时处理哦:" + currentTime);
            huaweiMessage.setNotification(notification);
            AndroidConfig androidConfig = new AndroidConfig();
            androidConfig.setCategory("WORK");
            androidConfig.setCollapse_key(0);
            androidConfig.setData("消息数据data");
            androidConfig.setTarget_user_type(1);
            AndroidNotification androidNotification = new AndroidNotification();
            androidNotification.setTitle("待办任务1");
            androidNotification.setImage("https://img0.baidu.com/it/u=3503816777,292249526&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400");
            androidNotification.setBody("1你有新的待办任务请及时处理哦:" + currentTime);
            androidNotification.setGroup("todoTask");
            ClickAction clickAction = new ClickAction();
            clickAction.setType(3);
            androidNotification.setClick_action(clickAction);
            androidConfig.setNotification(androidNotification);

            huaweiMessage.setAndroid(androidConfig);
        }


        HuaweiPushServer.send(messageBody, huaweiToken, new DataCallback<SendResponseBody>() {
            @Override
            public void onSuccess(SendResponseBody sendResponseBody) {
                ToastUtils.toastLong("消息发送成功");
            }

            @Override
            public void onFailure(String error) {
                ToastUtils.toastLong(error);
            }
        });
    }


}
